package com.cn.wang.pool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class MultiTask {	
	private static final Logger logger = Logger.getLogger(MultiTask.class);
	
	private static ExecutorService executorService = Executors.newFixedThreadPool(10);
	private List<Runnable> list = new ArrayList<Runnable>();
	
	public void add(Runnable ... runnables) throws NullPointerException{
		if(runnables.length>0){
			list = Arrays.asList(runnables);
		}else{
			return ;
		}
	}
	
	public void start(boolean await) throws InterruptedException{
		start(await,5000);
	}
	
	public void start(boolean await, final int timeout) throws InterruptedException{
		final CountDownLatch counter = await ? new CountDownLatch(list.size()) : null;
		for( int i=0;i<list.size();i++){
			final Runnable runnable = list.get(i);
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					runnable.run();
					if (counter != null)
						counter.countDown();
				}
			});
			
		}
		if (await) {
			if (timeout > 0) {
				counter.await(timeout, TimeUnit.MILLISECONDS);
			} else {
				counter.await();
			}
		}
	}
	
	public void shutdown() {
		list.clear();
	}

}
